//
//  ComposeViewController.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/12/2.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "ComposeViewController.h"


@implementation ComposeViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    PictureSelectorViewController *SelectorViewController = [[PictureSelectorViewController alloc]init];
    self.pictureSelectorController = SelectorViewController;
    EmoticonTextView *textview = [[EmoticonTextView alloc]init];
    textview.font = [UIFont systemFontOfSize:18];
    textview.textColor = [UIColor lightGrayColor];
    textview.backgroundColor = [UIColor lightGrayColor];
    //    保证视图是可滚动的,这样后面的keyboardDismissMode属性才可以使用
    textview.alwaysBounceVertical = true;
    //  向下拖拽,键盘就会消失  http://www.jianshu.com/p/7ec8f7b368b6
    textview.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.textView = textview;
    //    设置代理模式
    self.textView.delegate = self;
    [self setNavBar];
    [self setTextView];
//    添加工具条
    [self setBottomToolBar];
//    注册通知
    [self registerNotification];
    [self setPictureSelector];
}

- (void)registerNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self.textView selector:@selector(insetEmoticonText:) name:@"dianji" object:nil];
    
}
//移除通知
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//通知的相关方法
- (void)keyBoardWillChange:(NSNotification *)n{
//  在动画闭包中修改底部的工具条的约束
    NSDictionary *info = [n userInfo];
    //    获取动画进行的时间
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //    键盘弹出时的frame,需要转换为CGRectValue类型
//    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = -ScreenHeight + endKeyboardRect.origin.y;
//    设置动画曲线
//    NSInteger curve = [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView animateWithDuration:duration animations:^{
//        设置动画曲线
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [_toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.bottom).offset(height);
        }];
//        更新完约束,一定要调用layoutIfNeeded 方法
        [self.view layoutIfNeeded];
    }];
    
    
}
- (void)setBottomToolBar{
    UIToolbar *toolbar = [[UIToolbar alloc]init];
    self.toolBar = toolbar;
    NSArray *itemSettings = @[@{@"imageName":@"compose_toolbar_picture",@"actionName": @"selectPicture"},@{@"imageName": @"compose_mentionbutton_background"},@{@"imageName": @"compose_trendbutton_background"},@{@"imageName": @"compose_emoticonbutton_background", @"actionName": @"selectEmoticon"},@{@"imageName": @"compose_add_background"}];
    NSMutableArray *mutarray = [[NSMutableArray alloc]init];
    for (NSDictionary *dict in itemSettings) {
        NSString *imageName= dict[@"imageName"];
        self.actionName = NSSelectorFromString(dict[@"actionName"]);
        UIButton *btn = [[UIButton_Extesion alloc]initWithBackImageName:nil imageName:imageName];

        [btn addTarget:self action:_actionName forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *barbutton = [[UIBarButtonItem alloc]initWithCustomView:btn];
        [mutarray addObject:barbutton];
//        添加弹簧的item,这样的话按钮就会均匀排列,不会挤在一起
        UIBarButtonItem *space= [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [mutarray addObject:space];
    }
    self.items = mutarray;
    [self.items removeLastObject];
    NSLog(@"self.items = %@",self.items);
    self.toolBar.items = self.items;
    [self.view addSubview:_toolBar];
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(44);
    }];
}

- (void) setPictureSelector{
//   添加视图控制器
    [self addChildViewController:_pictureSelectorController];
//    添加视图控制器的视图
    [self.view addSubview:_pictureSelectorController.view];
    [self.view bringSubviewToFront:_toolBar];
    [_pictureSelectorController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(0);
    }];
}

- (void)selectPicture{
    [_pictureSelectorController.view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(ScreenHeight/3*2);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (EmoticonKeyBoardView *)keyBoardView{
    
    EmoticonKeyBoardView *keyBoardView = [[EmoticonKeyBoardView alloc]initWithselectEmoticon];
    
    return keyBoardView;
}

//添加emoji视图控制器
- (void)selectEmoticon{

    [self.textView resignFirstResponder];
    if(self.textView.inputView == nil){
     self.textView.inputView = self.keyBoardView;
    }else{
     self.textView.inputView = nil;
    }
    [self.textView becomeFirstResponder];
}
- (void)setTextView{

    [self.view addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat value = ScreenHeight/3;
        NSLog(@"self.superclass = %@",self.view);
        make.left.right.top.equalTo(self.view);
//    注意在头文件中引入宏定义,这样才可以在里面引入CGfloat的类型
        make.height.equalTo(value);
    }];
    
    UILabel *placeHolder = [UIlabel_extension factoryLabel:@"输入好玩的事吧" fontsize:18 textColor:[UIColor colorWithWhite:0.7 alpha:1]];
    self.placeHolder = placeHolder;
    [self.textView addSubview:_placeHolder];
    [_placeHolder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_top).offset(8);
        make.left.equalTo(self.textView.mas_left).offset(5);
    }];
    
}

- (void)setNavBar{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
    //    初始的时候设置发送按钮不能交互
    self.navigationItem.rightBarButtonItem.enabled = NO;
    UILabel *weiboTitle = [UIlabel_extension factoryLabel:@"发布微博" fontsize:18 textColor:[UIColor darkGrayColor]];
    UILabel *nameLabel = [UIlabel_extension factoryLabel:[AccountViewModel sharedAccountModel].userName fontsize:13 textColor:[UIColor lightGrayColor]];
    NSLog(@"[AccountViewModel sharedAccountModel].userName = %@",[AccountViewModel sharedAccountModel].userName);
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
    self.navigationItem.titleView = titleView;
    self.weiboTitle = weiboTitle;
    self.nameLabel = nameLabel;
    [self.navigationItem.titleView addSubview:_weiboTitle];
    [self.navigationItem.titleView addSubview:_nameLabel];
    [_weiboTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.centerX.equalTo(self.navigationItem.titleView);
    }];
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.bottom.equalTo(self.navigationItem.titleView);
    }];
}

//关闭页面
- (void)close{
    [self dismissViewControllerAnimated:true completion:nil];
}

//发布微博
- (void)send{
    NSString *urlstr = @"2/statuses/update.json";
    NSDictionary *parametres = @{@"access_token":[AccountViewModel sharedAccountModel].access_token,@"status":[self.textView fullText]};
    
    if(_pictureSelectorController.imageList.count > 0){
      NSString *urlString = @"https://upload.api.weibo.com/2/statuses/upload.json";
//        第一张图片的压缩二进制数据
//        NSData *imagedata = UIImagePNGRepresentation(self.pictureSelectorController.imageList.firstObject);
        
        //新浪微博的接口只允许上传单张图片  多张图片的接口是高级权限
        //将需要上传的文件转换为二进制的数据 拼接到 formData 中
        //1.data: 需要上传的文件的二进制数据
        //2.name: 服务器的接收字段名
        //3.fileName  服务器存储的文件名称  微博的服务器 会自己重写命名
        //4.mimeType: 文件格式  application/octet-stream: 八进制流 任意文件类型都可以
        //image/jpeg	 图片的文件格式

        [[HTTPClient sharedClient] POST:urlString parameters:parametres constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//            [formData appendPartWithFileData:imagedata name:@"pic" fileName:@"ooxxxxxx" mimeType:@"application/octet-stream"];
            NSUInteger index = 0;
            for (UIImage *image in self.pictureSelectorController.imageList) {
              NSData *imagedata = UIImagePNGRepresentation(image);
               [formData appendPartWithFileData:imagedata name:@"pic" fileName:[NSString stringWithFormat:@"fileName(%lu)",(unsigned long)index] mimeType:@"image/jpeg"];
                index ++;
            }
            
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [SVProgressHUD showSuccessWithStatus:@"发布微博成功"];
            [self close];
            NSLog(@"responseObject = %@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error = %@",error);
        }];
        
    }else{
    [[HTTPClient sharedClient] requestJSONDict:POST urlstring:urlstr parameters:parametres finished:^(NSDictionary *dict, NSError *error) {
        if (error != nil) {
            [SVProgressHUD showWithStatus:@"发送微博失败,请检查网络数据"];
            return ;
        }
        [self close];
    }];
    }
}

//实现代理方法
-(void)textViewDidChange:(UITextView *)textView{
//    如果用户输入了新文本,就隐藏占位符
    self.placeHolder.hidden = [_textView hasText];
//  根据是否输入的新文本决定右边的按钮是否可以响应
    self.navigationItem.rightBarButtonItem.enabled = [_textView hasText];
}
@end
